%% 创建储能系统（超级电容+隔离型DC/DC）
function create_energy_storage_system()
    % 初始化参数
    SVG_Star_10kV_System_Init;
    
    % 创建储能系统模型
    model_name = 'Energy_Storage_System';
    if bdIsLoaded(model_name)
        close_system(model_name, 0);
    end
    new_system(model_name);
    open_system(model_name);
    
    %% 1. 创建超级电容组
    create_supercapacitor_banks(model_name);
    
    %% 2. 创建隔离型DC/DC变换器
    create_isolated_dcdc_converters(model_name);
    
    %% 3. 创建SOC计算和管理
    create_soc_management(model_name);
    
    %% 4. 创建充放电控制
    create_charge_discharge_control(model_name);
    
    %% 5. 创建SOC均衡控制
    create_soc_balancing(model_name);
    
    %% 6. 创建保护功能
    create_protection_functions(model_name);
    
    % 保存模型
    save_system(model_name);
    disp(['储能系统模型 ' model_name ' 创建完成！']);
end

%% 子函数：创建超级电容组
function create_supercapacitor_banks(model_name)
    load('SVG_Parameters.mat');
    
    % 创建子系统
    add_block('built-in/Subsystem', [model_name '/Supercapacitor_Banks']);
    set_param([model_name '/Supercapacitor_Banks'], 'Position', [100 100 400 500]);
    
    subsys = [model_name '/Supercapacitor_Banks'];
    
    % 为每相每个H桥创建超级电容
    phases = {'A', 'B', 'C'};
    for i = 1:3
        for j = 1:N_bridge
            % 超级电容子系统
            sc_subsys = [subsys '/SC_' phases{i} num2str(j)];
            add_block('built-in/Subsystem', sc_subsys);
            set_param(sc_subsys, 'Position', [100+150*(i-1) 50+40*(j-1) 200+150*(i-1) 90+40*(j-1)]);
            
            % 进入超级电容子系统
            % 电容模型
            add_block('sps_lib/Passives/Series RLC Branch', [sc_subsys '/Supercapacitor']);
            set_param([sc_subsys '/Supercapacitor'], 'BranchType', 'C');
            set_param([sc_subsys '/Supercapacitor'], 'Capacitance', num2str(C_sc));
            
            % 初始电压源（用于设置初始SOC）
            add_block('sps_lib/Sources/DC Voltage Source', [sc_subsys '/Initial_Voltage']);
            set_param([sc_subsys '/Initial_Voltage'], 'Amplitude', num2str(Vsc_rated * SOC_init));
            
            % 内阻
            add_block('sps_lib/Passives/Series RLC Branch', [sc_subsys '/ESR']);
            set_param([sc_subsys '/ESR'], 'BranchType', 'R');
            set_param([sc_subsys '/ESR'], 'Resistance', '0.01');  % 10mΩ ESR
            
            % 电压测量
            add_block('sps_lib/Sensors and Measurements/Voltage Measurement', [sc_subsys '/V_meas']);
            
            % 电流测量
            add_block('sps_lib/Sensors and Measurements/Current Measurement', [sc_subsys '/I_meas']);
            
            % 输出端口
            add_block('built-in/Outport', [sc_subsys '/V_sc']);
            add_block('built-in/Outport', [sc_subsys '/I_sc']);
            add_block('built-in/Outport', [sc_subsys '/SOC']);
        end
    end
end

%% 子函数：创建隔离型DC/DC变换器
function create_isolated_dcdc_converters(model_name)
    load('SVG_Parameters.mat');
    
    % 创建子系统
    add_block('built-in/Subsystem', [model_name '/Isolated_DCDC_Converters']);
    set_param([model_name '/Isolated_DCDC_Converters'], 'Position', [500 100 800 500]);
    
    subsys = [model_name '/Isolated_DCDC_Converters'];
    
    % 为每相每个H桥创建DC/DC变换器
    phases = {'A', 'B', 'C'};
    for i = 1:3
        for j = 1:N_bridge
            % DC/DC子系统
            dcdc_subsys = [subsys '/DCDC_' phases{i} num2str(j)];
            add_block('built-in/Subsystem', dcdc_subsys);
            set_param(dcdc_subsys, 'Position', [100+150*(i-1) 50+40*(j-1) 200+150*(i-1) 90+40*(j-1)]);
            
            % 输入端口（超级电容侧）
            add_block('built-in/Inport', [dcdc_subsys '/V_sc_in']);
            add_block('built-in/Inport', [dcdc_subsys '/V_dc_ref']);
            
            % 双向Buck-Boost变换器（简化模型）
            % 原边开关
            add_block('sps_lib/Power Electronics/IGBT', [dcdc_subsys '/S1']);
            add_block('sps_lib/Power Electronics/IGBT', [dcdc_subsys '/S2']);
            
            % 高频变压器（简化为理想变压器）
            add_block('sps_lib/Passives/Linear Transformer', [dcdc_subsys '/HF_Transformer']);
            set_param([dcdc_subsys '/HF_Transformer'], 'NominalPower', num2str(P_dcdc_max));
            set_param([dcdc_subsys '/HF_Transformer'], 'Frequency', '20000');  % 20kHz
            set_param([dcdc_subsys '/HF_Transformer'], 'Winding1', '[1920 0.01 0]');
            set_param([dcdc_subsys '/HF_Transformer'], 'Winding2', '[950 0.01 0]');
            
            % 副边开关
            add_block('sps_lib/Power Electronics/IGBT', [dcdc_subsys '/S3']);
            add_block('sps_lib/Power Electronics/IGBT', [dcdc_subsys '/S4']);
            
            % 输出滤波电感
            add_block('sps_lib/Passives/Series RLC Branch', [dcdc_subsys '/L_filter']);
            set_param([dcdc_subsys '/L_filter'], 'BranchType', 'L');
            set_param([dcdc_subsys '/L_filter'], 'Inductance', '1e-3');
            
            % 输出滤波电容
            add_block('sps_lib/Passives/Series RLC Branch', [dcdc_subsys '/C_filter']);
            set_param([dcdc_subsys '/C_filter'], 'BranchType', 'C');
            set_param([dcdc_subsys '/C_filter'], 'Capacitance', '1e-3');
            
            % 控制系统
            add_block('built-in/Subsystem', [dcdc_subsys '/DCDC_Control']);
            
            % 输出端口（H桥侧）
            add_block('built-in/Outport', [dcdc_subsys '/V_dc_out']);
            add_block('built-in/Outport', [dcdc_subsys '/I_dc_out']);
        end
    end
end

%% 子函数：创建SOC计算和管理
function create_soc_management(model_name)
    % 创建子系统
    add_block('built-in/Subsystem', [model_name '/SOC_Management']);
    set_param([model_name '/SOC_Management'], 'Position', [100 600 400 800]);
    
    subsys = [model_name '/SOC_Management'];
    
    % 输入端口（所有超级电容的电压和电流）
    for i = 1:3
        for j = 1:11
            add_block('built-in/Inport', [subsys '/V_sc_' char(64+i) num2str(j)]);
            add_block('built-in/Inport', [subsys '/I_sc_' char(64+i) num2str(j)]);
        end
    end
    
    % SOC计算模块
    add_block('built-in/Subsystem', [subsys '/SOC_Calculation']);
    
    % 在SOC计算子系统中
    soc_calc = [subsys '/SOC_Calculation'];
    
    % 电压法SOC计算
    add_block('built-in/Fcn', [soc_calc '/SOC_Voltage']);
    set_param([soc_calc '/SOC_Voltage'], 'Expr', 'u/1920');  % SOC = V/V_rated
    
    % 库仑计数法SOC计算
    add_block('built-in/Integrator', [soc_calc '/Coulomb_Counting']);
    add_block('built-in/Gain', [soc_calc '/Capacity_Gain']);
    set_param([soc_calc '/Capacity_Gain'], 'Gain', '1/(15*1920)');  % 1/(C*V_rated)
    
    % SOC融合算法
    add_block('built-in/Subsystem', [soc_calc '/SOC_Fusion']);
    
    % 输出端口（所有超级电容的SOC）
    for i = 1:3
        for j = 1:11
            add_block('built-in/Outport', [subsys '/SOC_' char(64+i) num2str(j)]);
        end
    end
    
    % 平均SOC计算
    add_block('built-in/Sum', [subsys '/SOC_Sum']);
    add_block('built-in/Gain', [subsys '/SOC_Average']);
    set_param([subsys '/SOC_Average'], 'Gain', '1/33');  % 33个超级电容
    
    add_block('built-in/Outport', [subsys '/SOC_avg']);
end

%% 子函数：创建充放电控制
function create_charge_discharge_control(model_name)
    load('SVG_Parameters.mat');
    
    % 创建子系统
    add_block('built-in/Subsystem', [model_name '/Charge_Discharge_Control']);
    set_param([model_name '/Charge_Discharge_Control'], 'Position', [500 600 800 800]);
    
    subsys = [model_name '/Charge_Discharge_Control'];
    
    % 输入端口
    add_block('built-in/Inport', [subsys '/P_ref']);
    add_block('built-in/Inport', [subsys '/SOC_avg']);
    add_block('built-in/Inport', [subsys '/Grid_Status']);
    
    % 功率分配策略
    add_block('built-in/Subsystem', [subsys '/Power_Distribution']);
    
    % 充电控制
    add_block('built-in/Subsystem', [subsys '/Charge_Control']);
    
    % 在充电控制子系统中
    charge_ctrl = [subsys '/Charge_Control'];
    
    % SOC限制
    add_block('built-in/Saturation', [charge_ctrl '/SOC_Limit']);
    set_param([charge_ctrl '/SOC_Limit'], 'UpperLimit', num2str(SOC_max));
    set_param([charge_ctrl '/SOC_Limit'], 'LowerLimit', num2str(SOC_min));
    
    % 充电电流限制
    add_block('built-in/RateLimiter', [charge_ctrl '/Current_RateLimit']);
    set_param([charge_ctrl '/Current_RateLimit'], 'RisingSlewLimit', '100');  % A/s
    
    % 放电控制
    add_block('built-in/Subsystem', [subsys '/Discharge_Control']);
    
    % 自适应参考电压生成
    add_block('built-in/Subsystem', [subsys '/Adaptive_Vref']);
    
    % 在自适应参考电压子系统中
    vref_sys = [subsys '/Adaptive_Vref'];
    
    % 充电时降低参考电压
    add_block('built-in/Fcn', [vref_sys '/Charge_Vref']);
    set_param([vref_sys '/Charge_Vref'], 'Expr', '950 - 50*u');  % u是充电功率标幺值
    
    % 放电时提高参考电压
    add_block('built-in/Fcn', [vref_sys '/Discharge_Vref']);
    set_param([vref_sys '/Discharge_Vref'], 'Expr', '950 + 50*u');  % u是放电功率标幺值
    
    % 输出端口
    for i = 1:3
        for j = 1:11
            add_block('built-in/Outport', [subsys '/P_ref_' char(64+i) num2str(j)]);
            add_block('built-in/Outport', [subsys '/Vdc_ref_' char(64+i) num2str(j)]);
        end
    end
end

%% 子函数：创建SOC均衡控制
function create_soc_balancing(model_name)
    % 创建子系统
    add_block('built-in/Subsystem', [model_name '/SOC_Balancing']);
    set_param([model_name '/SOC_Balancing'], 'Position', [100 900 400 1100]);
    
    subsys = [model_name '/SOC_Balancing'];
    
    % 输入端口（所有SOC值）
    for i = 1:3
        for j = 1:11
            add_block('built-in/Inport', [subsys '/SOC_' char(64+i) num2str(j)]);
        end
    end
    
    % 相间均衡控制
    add_block('built-in/Subsystem', [subsys '/Inter_Phase_Balance']);
    
    % 相内均衡控制
    add_block('built-in/Subsystem', [subsys '/Intra_Phase_Balance']);
    
    % SOC差值计算
    add_block('built-in/MinMax', [subsys '/SOC_Max']);
    set_param([subsys '/SOC_Max'], 'Function', 'max');
    
    add_block('built-in/MinMax', [subsys '/SOC_Min']);
    set_param([subsys '/SOC_Min'], 'Function', 'min');
    
    add_block('built-in/Sum', [subsys '/SOC_Diff']);
    
    % 均衡控制器
    add_block('built-in/PID Controller', [subsys '/Balance_PI']);
    set_param([subsys '/Balance_PI'], 'Controller', 'PI');
    set_param([subsys '/Balance_PI'], 'P', '0.05');
    set_param([subsys '/Balance_PI'], 'I', '0.5');
    
    % 输出端口（功率修正值）
    for i = 1:3
        for j = 1:11
            add_block('built-in/Outport', [subsys '/P_balance_' char(64+i) num2str(j)]);
        end
    end
    
    % SOC差值监控
    add_block('built-in/Outport', [subsys '/SOC_Difference']);
end

%% 子函数：创建保护功能
function create_protection_functions(model_name)
    load('SVG_Parameters.mat');
    
    % 创建子系统
    add_block('built-in/Subsystem', [model_name '/Protection_Functions']);
    set_param([model_name '/Protection_Functions'], 'Position', [500 900 800 1100]);
    
    subsys = [model_name '/Protection_Functions'];
    
    % 输入端口
    for i = 1:3
        for j = 1:11
            add_block('built-in/Inport', [subsys '/V_sc_' char(64+i) num2str(j)]);
            add_block('built-in/Inport', [subsys '/I_sc_' char(64+i) num2str(j)]);
            add_block('built-in/Inport', [subsys '/SOC_' char(64+i) num2str(j)]);
        end
    end
    
    % 过压保护
    add_block('built-in/RelationalOperator', [subsys '/OV_Check']);
    set_param([subsys '/OV_Check'], 'Operator', '>');
    add_block('built-in/Constant', [subsys '/V_max']);
    set_param([subsys '/V_max'], 'Value', num2str(Vsc_rated * 1.1));
    
    % 欠压保护
    add_block('built-in/RelationalOperator', [subsys '/UV_Check']);
    set_param([subsys '/UV_Check'], 'Operator', '<');
    add_block('built-in/Constant', [subsys '/V_min']);
    set_param([subsys '/V_min'], 'Value', num2str(Vsc_rated * SOC_min));
    
    % 过流保护
    add_block('built-in/Abs', [subsys '/I_abs']);
    add_block('built-in/RelationalOperator', [subsys '/OC_Check']);
    set_param([subsys '/OC_Check'], 'Operator', '>');
    add_block('built-in/Constant', [subsys '/I_max']);
    set_param([subsys '/I_max'], 'Value', '500');  % 500A限制
    
    % SOC保护
    add_block('built-in/RelationalOperator', [subsys '/SOC_High_Check']);
    set_param([subsys '/SOC_High_Check'], 'Operator', '>');
    add_block('built-in/Constant', [subsys '/SOC_High_Limit']);
    set_param([subsys '/SOC_High_Limit'], 'Value', num2str(SOC_max));
    
    add_block('built-in/RelationalOperator', [subsys '/SOC_Low_Check']);
    set_param([subsys '/SOC_Low_Check'], 'Operator', '<');
    add_block('built-in/Constant', [subsys '/SOC_Low_Limit']);
    set_param([subsys '/SOC_Low_Limit'], 'Value', num2str(SOC_min));
    
    % 故障逻辑组合
    add_block('built-in/Logic', [subsys '/Fault_OR']);
    set_param([subsys '/Fault_OR'], 'Operator', 'OR');
    set_param([subsys '/Fault_OR'], 'Inputs', '5');
    
    % 输出端口
    add_block('built-in/Outport', [subsys '/Protection_Trip']);
    add_block('built-in/Outport', [subsys '/Fault_Status']);
end